﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StationUpdate
{
    public class JsonUtil
    {
        /// <summary>
        /// 对象转为json
        /// </summary>
        /// <typeparam name="ObjType"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjToJsonString<ObjType>(ObjType obj) where ObjType : class
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            //这里使用自定义日期格式，如果不使用的话，默认是ISO8601格式 
            //timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
            string s =  JsonConvert.SerializeObject(obj, Formatting.Indented, timeConverter);
            return s;
        }
        /// <summary>
        /// json转为对象
        /// </summary>
        /// <typeparam name="ObjType"></typeparam>
        /// <param name="JsonString"></param>
        /// <returns></returns>
        public static ObjType JsonStringToObj<ObjType>(string JsonString) where ObjType : class
        {
            JsonSerializerSettings jsetting = new JsonSerializerSettings();
            jsetting.NullValueHandling = NullValueHandling.Ignore;
            ObjType s = JsonConvert.DeserializeObject<ObjType>(JsonString, jsetting);
            return s;
        }
        
    }
}
